<template>
  <div>
    <el-upload
      class="upload-demo"
      ref="upload"
      multiple
      drag
      :action="$constant.qiniuUrl"
      :on-change="handleChange"
      :before-upload="beforeUpload"
      :on-success="handleSuccess"
      :on-error="handleError"
      :on-remove="handleRemove"
      :http-request="customUpload"
      :list-type="listType"
      :accept="accept"
      :limit="maxNumber"
      :auto-upload="false"
    >
      <div class="el-upload__text">
        <svg viewBox="0 0 1024 1024" width="40" height="40">
          <path
            d="M666.2656 629.4528l-113.7664-112.4864c-20.7872-20.5824-54.3232-20.5312-75.1104 0.1024l-113.3056 112.4864c-20.8896 20.736-21.0432 54.528-0.256 75.4688 20.736 20.8896 54.528 21.0432 75.4688 0.256l22.6304-22.4256v189.5936c0 29.44 23.9104 53.3504 53.3504 53.3504s53.3504-23.9104 53.3504-53.3504v-189.5424l22.6816 22.4256a53.1456 53.1456 0 0 0 37.5296 15.4112c13.7728 0 27.4944-5.2736 37.9392-15.8208 20.6336-20.9408 20.4288-54.7328-0.512-75.4688z"
            fill="#FFE37B"
          ></path>
          <path
            d="M820.992 469.504h-5.376c-3.072-163.328-136.3456-294.8096-300.4416-294.8096S217.856 306.1248 214.784 469.504H209.408c-100.7104 0-182.3744 81.664-182.3744 182.3744s81.664 182.3744 182.3744 182.3744h209.7664V761.856c-30.208 5.5808-62.464-3.3792-85.6576-26.7264-37.3248-37.5808-37.0688-98.5088 0.512-135.7824l113.3056-112.4864c37.2224-36.9664 97.8432-37.0176 135.168-0.1536l113.7664 112.4864c18.2272 18.0224 28.3648 42.0864 28.5184 67.7376 0.1536 25.6512-9.728 49.8176-27.7504 68.0448a95.40096 95.40096 0 0 1-68.3008 28.5184c-5.9392 0-11.776-0.512-17.5104-1.5872v72.3456h209.7664c100.7104 0 182.3744-81.664 182.3744-182.3744S921.7024 469.504 820.992 469.504z"
            fill="#8C7BFD"
          ></path>
        </svg>
        <div>拖拽上传 / 点击上传</div>
      </div>
      <template v-if="listType === 'picture'">
        <div slot="tip" class="el-upload__tip">
          一次最多上传{{ maxNumber }}张图片，且每张图片不超过{{ maxSize }}M！
        </div>
      </template>
      <template v-else>
        <div slot="tip" class="el-upload__tip">
          一次最多上传{{ maxNumber }}个文件，且每个文件不超过{{ maxSize }}M！
        </div>
      </template>
    </el-upload>

    <div style="text-align: center; margin-top: 20px">
      <el-button type="success" style="font-size: 12px" @click="submitUpload">
        上传
      </el-button>
    </div>
  </div>
</template>

<script setup lang='ts'>

import { ref } from "vue";

const props = defineProps({
  isAdmin: {
    type: Boolean,
    default: false,
  },
  prefix: {
    type: String,
    default: "",
  },
  listType: {
    type: String,
    default: "picture",
  },
  storeType: {
    type: String,
    default: localStorage.getItem("defaultStoreType"),
  },
  accept: {
    type: String,
    default: "image/*",
  },
  maxSize: {
    type: Number,
    default: 5,
  },
  maxNumber: {
    type: Number,
    default: 5,
  },
});
const uploadRef = ref(null);
const submitUpload = () => {
  uploadRef.value.submit();
};

const customUpload = async (options) => {
  let suffix = "";
  if (options.file.name.lastIndexOf(".") !== -1) {
    suffix = options.file.name.substring(options.file.name.lastIndexOf("."));
  }

  let key =
    prefix +
    "/" +
    (!isEmpty(currentUser.value.username)
      ? currentUser.value.username.replace(/[^a-zA-Z]/g, "") + currentUser.value.id
      : currentAdmin.value.username.replace(/[^a-zA-Z]/g, "") + currentAdmin.value.id) +
    new Date().getTime() +
    Math.floor(Math.random() * 1000) +
    suffix;

  if (storeType === "local") {
    let fd = new FormData();
    fd.append("file", options.file);
    fd.append("key", key);
    fd.append("relativePath", key);
    fd.append("type", prefix);
    fd.append("storeType", storeType);

    try {
      const response = await axios.post("/resource/upload", fd, {
        baseURL: "YOUR_BASE_URL", // 请将YOUR_BASE_URL替换为实际的后端地址
        headers: {
          Authorization: isAdmin
            ? localStorage.getItem("adminToken")
            : localStorage.getItem("userToken"),
        },
      });
      return response.data; // 根据实际情况返回response中的数据或者其他内容
    } catch (error) {
      return Promise.reject(error.message);
    }
  } else if (storeType === "qiniu") {
    try {
      const response = await axios.get("/qiniu/getUpToken?key=" + key, {
        baseURL: "YOUR_BASE_URL", // 请将YOUR_BASE_URL替换为实际的后端地址
        headers: {
          Authorization: isAdmin
            ? localStorage.getItem("adminToken")
            : localStorage.getItem("userToken"),
        },
      });
      const res = response.data;
      if (res !== null && res.hasOwnProperty("code") && res.code === 200) {
        options.data = {
          token: res.data,
          key: key,
        };
        return upload(options); // 你需要提供upload函数的具体实现
      } else if (res !== null && res.hasOwnProperty("code") && res.code !== 200) {
        return Promise.reject(res.message);
      } else {
        return Promise.reject("服务异常！");
      }
    } catch (error) {
      return Promise.reject(error.message);
    }
  }
};

const handleSuccess = (response, file, fileList) => {
  let url;
  if (storeType.value === "local") {
    url = response.data;
  } else if (storeType.value === "qiniu") {
    url = constant.value.qiniuDownload + response.key;
    common.saveResource(
      this,
      prefix.value,
      url,
      file.size,
      file.raw.type,
      "qiniu",
      isAdmin.value
    );
  }
  emit("addPicture", url);
};

const handleError = (err, file, fileList) => {
  message.error(err); // 使用Ant Design Vue的message组件显示错误信息
};
// 上传文件之前的钩子，参数为上传的文件，若返回 false 或者返回 Promise 且被 reject，则停止上传
const beforeUpload = (file) => {
  const isJPG = file.type === "image/jpeg" || file.type === "image/png";
  if (!isJPG) {
    message.error("上传图片只能是 JPG/PNG 格式!");
    return false;
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error("上传图片大小不能超过 2MB!");
    return false;
  }
  return true;
};

const handleRemove = (file, fileList) => {
  console.log(file, fileList);
};

const handleChange = (file, fileList) => {
  let flag = false;

  if (file.size > maxSize.value * 1024 * 1024) {
    message.warning(`图片最大为${maxSize.value}M！`);
    flag = true;
  }

  if (flag) {
    fileList.splice(fileList.length - 1, 1);
  }
};
</script>

<style scoped></style>
